'use client'

import { useEffect, useState } from 'react'
import { ToolForm } from './tool-form'
import type { Category } from '@/types'

export function ToolFormWrapper() {
  const [categories, setCategories] = useState<Category[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await fetch('/api/categories')
        const result = await response.json()
        
        if (response.ok && result.success) {
          setCategories(result.data || [])
        } else {
          throw new Error(result.error || '获取分类失败')
        }
      } catch (err: any) {
        setError(err.message)
        // 使用静态数据作为后备
        setCategories([
          { id: '1', name: '开发工具', description: '编程开发相关的实用工具', icon: '💻', createdAt: new Date(), updatedAt: new Date() },
          { id: '2', name: '设计工具', description: '设计和创意相关的工具', icon: '🎨', createdAt: new Date(), updatedAt: new Date() },
          { id: '3', name: '效率工具', description: '提升工作效率的实用工具', icon: '⚡', createdAt: new Date(), updatedAt: new Date() },
          { id: '4', name: '娱乐游戏', description: '休闲娱乐和小游戏', icon: '🎮', createdAt: new Date(), updatedAt: new Date() },
          { id: '5', name: '学习教育', description: '学习和教育相关的工具', icon: '📚', createdAt: new Date(), updatedAt: new Date() },
          { id: '6', name: '生活服务', description: '日常生活实用工具', icon: '🏠', createdAt: new Date(), updatedAt: new Date() }
        ])
      } finally {
        setLoading(false)
      }
    }

    fetchCategories()
  }, [])

  if (loading) {
    return (
      <div className="w-full max-w-2xl mx-auto">
        <div className="bg-white rounded-lg shadow-sm border p-6 animate-pulse">
          <div className="h-6 bg-gray-200 rounded w-1/3 mb-4"></div>
          <div className="space-y-4">
            <div className="h-4 bg-gray-200 rounded w-1/4"></div>
            <div className="h-10 bg-gray-200 rounded"></div>
            <div className="h-4 bg-gray-200 rounded w-1/4"></div>
            <div className="h-20 bg-gray-200 rounded"></div>
            <div className="h-4 bg-gray-200 rounded w-1/4"></div>
            <div className="h-10 bg-gray-200 rounded"></div>
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="w-full max-w-2xl mx-auto">
        <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
          <h3 className="text-lg font-medium text-red-800 mb-2">加载失败</h3>
          <p className="text-red-600 mb-4">{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700"
          >
            重试
          </button>
        </div>
      </div>
    )
  }

  return <ToolForm categories={categories} />
}
